<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import Toc from '../components/Toc.vue';

const activeId = ref('');
const route = useRoute()

const { data: page } =   useAsyncData('page-' + route.path, () => {
  return queryCollection('content').path(route.path).first()
})



// 关于右侧目录的
// 将树形结构扁平化为数组，用于渲染内容区域
const sections = computed(() => {
  const flatten = (nodes:any) => {
    let result: { id: string; text: string; depth: number; children: any[] }[] = [];
    nodes.forEach((node:any) => {
      result.push({
        id: node.id,
        text: node.text,
        depth: node.depth,
        children: node.children ? flatten(node.children) : []
      });
    });
    return result;
  };
  return flatten(page.value?.body?.toc?.links || []);
});

const setActiveId = (id:any) => {
  activeId.value = id;
};

// 滚动检测函数 - 更新当前激活项
const handleScroll = () => {
  const contentSections = document.querySelectorAll('[id]');
  let current:any = '';
  
  contentSections.forEach((section:any) => {
    const sectionTop = section.offsetTop;
    if (window.pageYOffset >= sectionTop - 100) {
      current = section.getAttribute('id');
    }
  });
  
  if (current) {
    activeId.value = current;
  }
};

onMounted(() => {
  window.addEventListener('scroll', handleScroll);
  
  // 设置初始激活项（第一个项目）
  if (sections.value.length > 0 && sections.value[0]?.id) {
    activeId.value = sections.value[0].id ?? '';
  }
  
  // 处理页面加载时的锚点定位
  const hash = window.location.hash.replace('#', '');
  if (hash) {
    setTimeout(() => {
      scrollToAnchor(hash);
      setActiveId(hash);
    }, 300);
  }
});

onBeforeUnmount(() => {
  window.removeEventListener('scroll', handleScroll);
});

// 滚动到锚点位置（与Toc组件中相同，用于页面加载时定位）
const scrollToAnchor = (id:any) => {
  const target = document.getElementById(id);
  if (target) {
    const headerHeight = document.querySelector('header')?.offsetHeight || 0;
    const topPosition = target.getBoundingClientRect().top + window.pageYOffset - headerHeight - 16;
    
    window.scrollTo({
      top: topPosition,
      behavior: 'smooth'
    });
  }
};
//打印页面路径和标题


// function transformToItems(data: any): any[] {
//   // 将 data 打印为 JSON 字符串
//   const stringify = JSON.stringify(data, null, 2);
//   console.log('Transforming data:', stringify);
//   // 递归映射函数，处理任意层级
//   const mapNode = (node: any) => {
//     const result: any = {
//       label: node.text,
//       defaultExpanded: true, // 默认展开所有节点
//       icon: '', // 使用默认图标
//       slot: 'app' as const,
//       // 如果有链接，则使用链接，否则使用空字符串
//     };
    
//     // 如果存在子节点，递归映射子节点
//     if (node.children && node.children.length > 0) {
//       result.children = node.children.map(mapNode);
//     }
    
//     return result;
//   };

//   // 处理顶层节点
//   return data.links.map(mapNode);
// }


// const items = computed(() => {
//   if (page.value?.body?.toc?.links) {
//     return transformToItems({
//       links: page.value.body.toc.links
//     });
//   }
//   return [];
// });
</script>

<template>
  <div class="container">
    <!-- 内容区域 -->
    <ContentRenderer 
      class="markdown-content prose max-w-none py-8 flex-grow"
      v-if="page"
      :value="page"
    />
    <Toc 
            :nodes="page?.body?.toc?.links || []" 
            :active-id="activeId"
            @item-clicked="setActiveId"
          />

    <!-- TOC 区域 -->
    <!-- <div class="toc-container">
      <UTree trailing-icon='' :items="items" >
        <template #app="{ item }">
            <a class="" src="#"
                :href="`#${item.label}`"
               v-text="item.label"
               style="color:var(--ui-text);">
            </a>
        </template>
      </UTree>
    </div> -->


  </div>
</template>

<style>
@import url("~/assets/css/wx.css");
</style>

<style scoped>

.container {
  display: flex;
}



.toc-container {
  width: 280px; /* 固定宽度 */
  flex-shrink: 0; /* 防止收缩 */
  margin-left: 20px; /* 间距 */
  position: sticky;
  top: 1rem;
  align-self: flex-start; /* 顶部对齐 */
  max-height: 100vh;
  overflow-y: auto;
  padding: 1rem;
}
</style>